package com.feicheng.iou.service.impl.weChat;

import com.feicheng.iou.bean.InformationBean;
import com.feicheng.iou.constant.StatusCodeConstant;
import com.feicheng.iou.controller.weChat.util.WechatPayConfig;
import com.feicheng.iou.exception.SystemExceptionV110;
import com.feicheng.iou.result.ResultInfoV110;
import com.feicheng.iou.service.weChatService.WeChatLoginService;
import com.feicheng.iou.util.HttpClientUtils;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WeChatLoginServiceImpl implements WeChatLoginService {
    /**
     * @param code 授权码
     * @param state 用户自定义参数,原样返回
     * @description  调用微信授权接口,根据获取到的code换区openid
     * @return ResultInfoV110
     */
    @Override
    public ResultInfoV110 getOpenId(String code, String state) {
        log.info("进入WeChatLoginServiceImpl的getOpenId方法,获取授权后的回调地址,redirect_uri/code=CODE&state=STATE,参数code="+code+",参数state="+state);
        //TODO:判断session中是否有openid(或者直接从数据库获取?) 如果有直接返回openid 如果没有则重新获取
        //作为参数获取code state
        // https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
        String accessTokenUrl = WechatPayConfig.GATEWAY   //公众号方式
                +"?appid="+WechatPayConfig.APPID
                +"&secret="+WechatPayConfig.APP_SECRET
                +"&code="+code
                +"&grant_type=authorization_code";
        log.info("appid="+WechatPayConfig.APPID+","+"secret="+WechatPayConfig.APP_SECRET);
        String result = null;
        try {
            //2.执行请求:获取微信请求返回数据(openId)
            result = new HttpClientUtils().get(accessTokenUrl);
            log.info("执行登录返回的信息是:"+"code="+code+",result="+result);
            //3.对微信返回的数据进行转换
            Gson gson = new Gson();
            Map<String,Object> resultMap = gson.fromJson(result, HashMap.class);

            //4:解析微信用户获得唯一凭证openId
            String openid = (String)resultMap.get("openid");
            //TODO 将openid放入到session中
            //TODO 将openid存入数据库的student表的openid字段
            log.info("获取到的openid为"+openid);
            //封装返回
            return ResultInfoV110.success(resultMap);
        } catch (Exception e) {
             throw new SystemExceptionV110(InformationBean.setInformationBean(StatusCodeConstant.F001,"获取openid"));
        }
    }
}
